﻿<%@ WebHandler Language="C#" Class="HomeworkHandler" %>

using System;
using System.Web;
using System.IO;
using System.Collections.Generic;

using EHSubmit.Logic;
using EHSubmit.Model;
using EHSubmit.Util;

public class HomeworkHandler : BaseAjaxHandler
{
    protected override void Mapping()
    {
        //// 此方法为学生调用,返回所有该学生提交过的作业,需要验证学生身份
        OprationMap["list_stu"] = "ListFromStudent";         //列出可选(需要提交)的作业
        
        OprationMap["list_teacher"] = "ListFromTeacher";     //列出老师要批改的作业
        OprationMap["Mark"] = "MarkHomework";                //老师给作业打分
    }

    public void ListFromStudent()
    {

        if (Validate(ERole.Student))
        {
            HomeworkManager manager = new HomeworkManager();
            /// 根据学生ID,取该学生已提交的所有作业,
            /// TODO------
            //IList<EHSubmit.Model.Goal> goals = manager.G(CurrentUser.ID, 1);  //暂时取第一页

            //string jsonGoals = JsonHelper.Serialize(goals);

            //int count = manager.get
            int start = WebHelper.IntSafeConvert(Context.Request["start"], 0);
            int limit = WebHelper.IntSafeConvert(Context.Request["limit"], 0);
            int page = start / limit + 1;
            
            int count = manager.GetCountFromStudent(CurrentUser.ID);
            IList<Homework> works = manager.ListByPageFromStudent(CurrentUser.ID, page, limit);

            string jsonWorks = JsonHelper.Serialize(works);

            IsSuccess = true;

            ResponseText = "{" + string.Format("count:{0},data:{1}", count, jsonWorks) + "}";
        }
        else
        {
            Message = Constants.INFO_NO_ACCESS;
        }
    }

    public void ListFromTeacher()
    {
        if (Validate(ERole.Teacher))
        {
            HomeworkManager manager = new HomeworkManager();

            string goalID = Context.Request["goalID"].ToString();
            int start = WebHelper.IntSafeConvert(Context.Request["start"], 0);
            int limit = WebHelper.IntSafeConvert(Context.Request["limit"], 0);
            int page = start / limit + 1;
            
            int type = WebHelper.IntSafeConvert(Context.Request["type"], -1);
            int count = 0;
            IList<Homework> works = new List<Homework>();
            //获取要批改的作业
            if (type == 0)
            {
                count = manager.GetCountFromTeacher(goalID, true);
                works = manager.ListByPageFromTeacher(goalID, page, limit, true);
                IsSuccess = true;
            }
            //获取已批改的作业
            else if(type == 1)
            {
                count = manager.GetCountFromTeacher(goalID, false);
                works = manager.ListByPageFromTeacher(goalID, page, limit,false);
                IsSuccess = true;
            }
            else
            {
                IsSuccess = false;
                Message = Constants.INFO_UNKNOWN_ERR;
            }
            
            if (IsSuccess)
            {
                string jsonWorks = JsonHelper.Serialize(works);
                ResponseText = "{" + string.Format("count:{0},data:{1}", count, jsonWorks) + "}";
            }

        }
        else
        {
            Message = Constants.INFO_NO_ACCESS;
        }
    }

    public void MarkHomework()
    {
        if (Validate(ERole.Teacher))
        {
            int hwID = WebHelper.IntSafeConvert(Context.Request["hwID"], 0);
            if (hwID != 0)
            {
                HomeworkManager hwManager = new HomeworkManager();
                Homework homework = hwManager.GetHomework(hwID);
                homework.Scores = WebHelper.IntSafeConvert(Context.Request["score"],-1);
                homework.Comment = Context.Request["comment"].ToString();
                homework.CommentTime = DateTime.Now;
                hwManager.UpdateHomework(homework);
                IsSuccess = true;
                ResponseText = "{success:true,msg:'提交成功!'}";
            }
            else
            {
                IsSuccess = false;
                Message = "无该作业!";
            }
        }
        else
        {
            Message = Constants.INFO_NO_ACCESS;
        }
    }
    /// <summary>
    /// 添加作业(此方法写在UploadHandler中)
    /// </summary>
    //public override void Add()
    //{
        
    //}


    /// <summary>
    /// 修改作业
    /// </summary>
    public override void Update()
    {
        if (Validate(ERole.Student))
        {
            try
            {
                int wid = int.Parse(Context.Request["workId"]);
                int goalId = int.Parse(Context.Request["goalId"]);

                HomeworkManager manager = new HomeworkManager();

                //------------------------------------------------------------------------
                //-------------------------数据、权限验证---------------------------------
                // 获得该作业原来信息
                Homework work = manager.GetHomework(wid);

                //不存在此作业
                if (work == null)
                {
                    Message = "不存在此作业";
                    return;
                }

                // 不能修改别人的作业
                if (work.StudentID != CurrentUser.ID)
                {
                    Message = Constants.INFO_NO_ACCESS;
                    return;
                }

                //------------------------------------------------------------------------
                //-------------------------------文件更新---------------------------------

                // 获得上传请求中的文件（单个文件）
                HttpPostedFile postedFile = Context.Request.Files[0];
                string fileName = postedFile.FileName;                   // 取得文件名
                
                // 选择了文件则重新上传，否则不上传文件
                if (fileName != null && fileName != string.Empty)
                {

                    string ext = System.IO.Path.GetExtension(fileName);      // 获得后缀名

                    // 获得Goal实例,布置作业的信息
                    GoalManager gManager = new GoalManager();
                    EHSubmit.Model.Goal goal = gManager.GetGoal(goalId);

                    //if (!goal.AllowedFileTypes.Contains(ext){
                    //     throw new Exception("只能传输的文件格式为:" + goal.AllowedFileTypes);  
                    //}

                    string reqstGoalPath = FileHelper.GenerateGoalPath(CurrentUser, goal);    // 将要上传的虚拟目录
                    string realGoalPath = Context.Server.MapPath(reqstGoalPath);              // 上传的物理目录
                    string attachFileName = FileHelper.GenerateFileName(CurrentUser, ext);
                    string attachPath = realGoalPath + attachFileName;       // 文件物理地址


                    // 创建目录
                    if (!Directory.Exists(realGoalPath))
                    {
                        Directory.CreateDirectory(realGoalPath);
                    }
                    //保存文件
                    postedFile.SaveAs(attachPath);

                    //更新文件路径信息
                    work.AttachPath = reqstGoalPath + attachFileName;
                }

                //------------------------------------------------------------------------
                //-------------------------------作业信息更新-----------------------------

                work.GoalID = goalId;
                work.GoalName = Context.Request["goalTitle"];
                work.Description = Context.Request["description"];
                work.UpdateTime = DateTime.Now;

                //修改
                manager.UpdateHomework(work);


                IsSuccess = true;
                ResponseText = "{success:true,msg:'添加成功！'}";
            }
            catch (Exception e)
            {
                Message = e.Message;
            }
        }
        else
        {
            Message = Constants.INFO_NO_ACCESS;
        }


    }
    
    
    /// <summary>
    /// 删除作业
    /// </summary>
    public override void Delete()
    {
        int hid = int.Parse(Context.Request["hid"]);

        if (Validate(ERole.Student))
        {
            HomeworkManager manager = new HomeworkManager();

            try
            {
                //获得要删除的作业对象
                Homework work = manager.GetHomework(hid);

                // 不能删除别人的作业
                if (CurrentUser.ID == work.StudentID)
                {
                    // 是本学生删除自己的作业
                    manager.CompletelyDeleteHomework(work);

                    // 标志 执行成功
                    IsSuccess = true;
                    ResponseText = "{success:true,msg:'删除成功！'}";
                }
                else   // 该生想删除他人作业
                {
                    Message = Constants.INFO_NO_ACCESS;
                }

            }
            catch (Exception e)
            {
                Message = e.Message;
            }
        }
        else
        {
            Message = Constants.INFO_NO_ACCESS;
        }
    }
 

}